import { AdminService } from './../admin/admin.service';
import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';

@Injectable()
export class AccessService {
    constructor(@InjectModel('Access') private readonly accessModel, private readonly adminService: AdminService) {}

    async find(where = {}, fields = null) {
        return await this.accessModel.find(where, fields);
    }
    async create(accessInfo) {
        return await this.accessModel.create(accessInfo);
    }
    async update(accessInfo) {
        return await this.accessModel.updateOne({ _id: accessInfo._id }, accessInfo);
    }
    async delete(accessInfo) {
        const lookupResult = (
            await this.accessModel.aggregate([
                { $match: { _id: new mongoose.Types.ObjectId(accessInfo._id) } },
                { $lookup: { localField: '_id', foreignField: 'module_id', as: 'children', from: 'access' } },
            ])
        )[0];
        if (lookupResult.children?.length) {
            throw new BadRequestException('不可删除父节点');
        }
        return await this.accessModel.deleteOne(accessInfo);
    }
    getModel() {
        return this.accessModel;
    }
    async getMenu(req) {
        return this.adminService.getMenu(req);
    }
}
